package com.start.common.dataImport;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSONObject;
import com.start.common.dic.DictMapperParams;
import com.start.common.dic.StartBaseDicMapperHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * excel 导出
 */
@Slf4j
public class StartStartExcelExport extends StartBaseExcelActionData  {
    private DictMapperParams dictMapperParams;
    private ExcelWriter writer;
    private long currentCount;
    private volatile boolean isStart;
    private StartExcelExportListener listener;

    public void setListener(StartExcelExportListener listener) {
        if (isStart) {
            log.error("导出任务已开始，禁止设置数据监听");
            return;
        }
        this.listener = listener;
    }

    public StartStartExcelExport(DictMapperParams dictMapperParams) {
        this(dictMapperParams, null);
    }

    public StartStartExcelExport(DictMapperParams dictMapperParams, StartExcelExportListener listener) {
        this.dictMapperParams = dictMapperParams;
        this.listener = listener;
    }


    protected void writeRow(JSONObject object) {
        if (!isStart) {
            throw new RuntimeException("请先调用start方法");
        }
        Map<String, StartBaseDicMapperHandler> handlerMap = dictMapperParams.getHandlerFiled();
        Set<String> keySet = handlerMap.keySet();
        Map<String, Object> data = new HashMap<>();
        for (String key : keySet) {
            if (!object.containsKey(key)) {
                continue;
            }
            StartBaseDicMapperHandler handler = handlerMap.get(key);
            String exportValue = handler.getExportValue(object);
            data.put(key, exportValue);
        }
        currentCount++;
        this.onRow(data, currentCount);
    }


    private void onRow(Map<String, Object> row, long currentCount) {
        if (writer != null) {
            writer.writeRow(row, true);
            return;
        }
        if (listener == null) {
            return;
        }
        listener.onRow(row, currentCount);
    }


    public void onEnd() {
        if (listener != null) {
            listener.onEnd(writer);
        }
    }

    @Override
    public void start() {
        if (isStart) {
            return;
        }

        if (listener == null) {
            return;
        }
        isStart = true;
        listener.onStart();
        if (!listener.isCustom()) {
            writer = ExcelUtil.getWriter();
            writer.setHeaderAlias(dictMapperParams.getHeaderAlias());
            writer.writeRow(dictMapperParams.getHeaderAlias().values());
        }


    }
}
